package com.javasm.bootcrud01.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.javasm.bootcrud01.UserAccess.dao.UserAccessLogDao;
import com.javasm.bootcrud01.UserAccess.entity.UserAccessLog;
import com.javasm.bootcrud01.user.entity.WebUser;
import com.javasm.bootcrud01.user.dao.WebUserDao;
import com.javasm.bootcrud01.user.service.WebUserService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * (WebUser)表服务实现类
 *
 * @author makejava
 * @since 2025-07-03 08:11:15
 */
@Service("webUserService")
public class WebUserServiceImpl implements WebUserService {


    @Resource
    private WebUserDao webUserDao;

    @Resource
    UserAccessLogDao  userAccessLogDao;

    @Resource
    RedisTemplate<String,String>  redisTemplateString;

    @Override
    public WebUser queryById(Integer uid) {

        return this.webUserDao.queryById(uid);
    }

    @Override
    public Long countUsers(Map<String, Object> params) {
        return this.webUserDao.count(params);
    }

    @Override
    public WebUser insert(WebUser webUser) {
        this.webUserDao.insert(webUser);

//        //数据存在redis中
//        String  s = JSON.toJSONString(webUser);
//        redisTemplateString.opsForValue().set("user:test:str",s);
        return webUser;
    }

    @Override
    public WebUser update(WebUser webUser) {
        this.webUserDao.update(webUser);
        WebUser webUser1 = webUserDao.queryById(webUser.getUid());
        return webUser1;
    }

    @Override
    public WebUser deleteByUid(Integer uid) {
        WebUser webUser1 = webUserDao.queryById(uid);
        webUserDao.deleteById(uid);
        return webUser1;
    }

    @Override
    public List<WebUser> deleteByIDsss(List<Integer> uids) {
        List<WebUser> deletedUsers = new ArrayList<>();


        for (Integer uid : uids) {

            WebUser webUser = webUserDao.queryById(uid);
            if (webUser != null) {
                deletedUsers.add(webUser);
            }
        }
        if (!deletedUsers.isEmpty()) {
            webUserDao.deleteBYIDS(uids);
        }
        return deletedUsers;
    }

    @Resource
    RedisTemplate<String, Object> redisTemplate;
    @Override
    public List<WebUser> queryByparams(WebUser webUser) {
        return this.webUserDao.queryByparams(webUser);


    }

    @Override
    public int batchInsert(List<WebUser> webUsers) {
        int i = webUserDao.batchInsert(webUsers);
        return i;
    }

    @Override
    public int batchUpdate(List<WebUser> webUsers) {
        int i = webUserDao.batchUpdate(webUsers);
        return i;
    }

    @Override
    public List<WebUser> batchQueryall(List<Integer> list) {

        List<WebUser>  queryalls  = new ArrayList<>();
        if (list == null || list.isEmpty()) {
            return Collections.emptyList();
        }

        return   webUserDao.batchqueryByIDs(list);

    }

    @Transactional
    @Override
    public PageInfo<WebUser> listPage(Integer pageSize, Integer pageNum) {
        //开启分页
        PageHelper.startPage(pageNum,pageSize);
        //查询全部
        List<WebUser> webUsers = webUserDao.queryAll();
        PageInfo<WebUser>  pageInfo  =  new PageInfo<>(webUsers);
        return pageInfo;
    }

    @Override
    @Transactional
    public WebUser queryUserWithAccessLog(Integer uid) {
        //1查询用户信息
        WebUser User = webUserDao.queryById(uid);
        if(User == null){
            throw new RuntimeException("用户不存在");
        }
        //2插入访问日志
        UserAccessLog userAccessLog = new UserAccessLog();
        userAccessLog.setUserId(uid);
        userAccessLog.setOperation("查询了用户信息");
        LocalDateTime now = LocalDateTime.now(ZoneId.of("UTC"));
        Date accessTime = Date.from(now.atZone(ZoneId.of("UTC")).toInstant());
        userAccessLog.setAccessTime(accessTime);
        userAccessLogDao.insert(userAccessLog);
        //3.故意抛出异常，触发回滚
        if (uid.equals(10086)) {
            throw new RuntimeException("故意抛出异常，测试事务回滚");
        }
        return User;
    }



    @Override
    public List<WebUser> listWithRedis() {
        List<WebUser>  list = webUserDao.queryALLData();
        //引入Redis
        String  key = "userr:list";
        for (WebUser user : list){
            redisTemplate.opsForList().leftPush(key,user);
        }
        return  list;

    }

    @Override
    public void insertwithRedis(WebUser webUser) {
            //保存到数据库中
        insert(webUser);

        //保存到Redis中
        String  key = "gift:list";
        redisTemplate.opsForList().rightPush(key,webUser);

    }

    @Override
    public PageInfo<WebUser> listPagewithRedis(Integer pageNum, Integer pageSize) {
        String key = "userr:list："+ pageNum + ":" + pageSize;
        //尝试从Redis中获取缓存
        List<WebUser>  cachedUsers =(List<WebUser>) redisTemplate.opsForValue().get(key);
        if(cachedUsers != null &&  !cachedUsers.isEmpty()){
            return new PageInfo<>(cachedUsers);
        }
            //缓存未命中，就是从数据库中查询
        PageHelper.startPage(pageNum,pageSize);
        List<WebUser> webUsers = webUserDao.queryAll();
        PageInfo<WebUser> pageInfo = new PageInfo<>(webUsers);
        //写入Redis缓存
        redisTemplate.opsForValue().set(key,webUsers,1, TimeUnit.HOURS);

        return pageInfo;
    }


}

    //
//    @Override
//    public WebUser queryById(Integer uid) {
//        return null;
//    }
//
//    @Override
//    public WebUser insert(WebUser webUser) {
//        return null;
//    }
//
//    @Override
//    public WebUser update(WebUser webUser) {
//        return null;
//    }
//
//    @Override
//    public boolean deleteById(Integer uid) {
//        return false;
//    }

